package com.birdboot.core;

import com.birdboot.annotation.Controller;
import com.birdboot.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 该类维护请求路径与对应的Controller方法的关系
 */
public class HandlerMapping {
    /*
        key:请求路径                    例如:"/regUser"
        value:处理该请求的业务方法             UserController的reg()方法
     */
    private static Map<String, Method> mapping = new HashMap<>();

    static {
        initMapping();
    }

    private static void initMapping(){
        try {
            File baseDir = new File(
                HandlerMapping.class.getClassLoader().getResource(".").toURI()
            );
            File dir = new File(baseDir,"com/birdboot/controller");
            File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
            for(File sub : subs){
                String fileName = sub.getName();
                String className = fileName.replace(".class","");
                Class cls = Class.forName("com.birdboot.controller."+className);
                //判断该类是否被注解@Controller标注?
                if(cls.isAnnotationPresent(Controller.class)){
                    //获取所有方法
                    Method[] methods = cls.getDeclaredMethods();
                    for(Method method : methods){
                        //判断该方法是否被注解@RequestMapping标注?
                        if(method.isAnnotationPresent(RequestMapping.class)){
                            //获取@RequestMapping注解参数
                            RequestMapping rm = method.getAnnotation(RequestMapping.class);
                            String value = rm.value();
                            //将该方法处理的请求路径作为key(注解参数)将该方法对象作为value存入mapping
                            mapping.put(value, method);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据请求路径获取处理该请求的某个Controller下的对应方法
     * @param path
     * @return
     */
    public static Method getMethod(String path){
        return  mapping.get(path);
    }

    public static void main(String[] args) {
        Method method = mapping.get("/regUser");
        System.out.println(method);
    }

}
